/**
 * 
 * 
 * 
 **/
//内网地址
//var httpUrl="http://192.168.0.109:8008/api/";
//var request_url ="http://192.168.0.109:8008";

//外网地址
var httpUrl="http://mels.zhongdijinxin.com/api/";
var request_url ="http://mels.zhongdijinxin.com";

var _currentuser;

var durations =  mui.os.ios ? 500 : 100; //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
var deceleration = mui.os.ios ? 0.003 : 0.0002;	//阻尼系数

/*test webview*/
//webviewLog();
function webviewLog(){
	mui.plusReady(function(){
		var array = plus.webview.all();
		if(array){
			for(var i=0,len=array.length;i<len;i++){
			    	console.log(i+ " id:" +array[i].id +" url:" +array[i].getURL());
		        }
		} 
	});
}
/*test webview*/
function log(str)
{
	var self = plus.webview.currentWebview();
	console.log("id:"+self.id +" info:"+str);
}
							



function trim(str){ //删除左右两端的空格
	 return str.replace(/(^\s*)|(\s*$)/g, "");
 }
		
		
/*根据id查找元素*/
function $id(id) {
	return document.getElementById(id);
}


(function($, owner) {
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.username = loginInfo.username || '';
		loginInfo.password = loginInfo.password || '';
		if (loginInfo.username.length < 5) {
			return callback('账号最短为 5 个字符');
		}
		if (loginInfo.password.length < 6) {
			return callback('密码最短为 6 个字符');
		}
//		var users = JSON.parse(localStorage.getItem('$users') || '[]');
//		var authed = users.some(function(user) {
//			return loginInfo.account == user.account && loginInfo.password == user.password;
//		});
        console.log(JSON.stringify(loginInfo));  
        ajax_login(loginInfo ,callback);
         
//		if (authed) {
//			return owner.createState(loginInfo.account, callback);
//		} else {
//			return callback('用户名或密码错误');
//		}
	};

	owner.createState = function(name, callback) {
		var state = owner.getState();
		state.account = name;
		state.token = "token123456789";
		state.nickname = name;
		state.id="";
		state.telephone ="";
		owner.setState(state);		
		
		return callback();
	};

	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if (regInfo.username.length < 5) {
			return callback('用户名最短需要 5 个字符');
		}
		if (regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		if (!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		}
//		var users = JSON.parse(localStorage.getItem('$users') || '[]');
//		users.push(regInfo);
//		localStorage.setItem('$users', JSON.stringify(users));
//				
		
		//联网注册
		ajax_register(regInfo);						
		
		return callback();
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		   // alert(stateText);//
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if (!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = localStorage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	}
}(mui, window.app = {}));



(function(w){
	//获取sessionKey
//	w.ajax_get_SessionKey = function(){
//		mui.ajax('http://182.140.244.73:91/sessionkey',{
//			dataType:'json',//服务器返回json格式数据
//			type:'get',//HTTP请求类型
//			timeout:10000,//超时时间设置为10秒；
//			success:function(data){
//				logData(data);
//				localStorage.setItem('session_key',data.session_key);
//				//关闭启动页面
//				closeStartScreent();
//			},
//			error:function(xhr,type,errorThrown){
//				
//			}
//		});
//	};
	
	//用户注册
	w.ajax_register = function(options){
		//var data = getdata(options,'com.huihoo.user.register');
		var data = JSON.stringify(options);
		var Url = httpUrl + "usermemberreg/"
		mui.ajax(Url,{
			data:data,
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){
				//logData(data);
				//registerSeccess(data);
				if(data.result=="savesuccess")
				{
					mui.toast("注册成功！");
				}
				else
				{
					mui.toast("服务器异常！");
				}
			},
			error:function(xhr,type,errorThrown){
				
			}
		});
	}
	
	
	//用户登陆
	w.ajax_login = function(options,callback){
		var data = JSON.stringify(options);
		var Url = httpUrl + "usermemberlogin/"
		mui.ajax(Url,{
			data:data,
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){
				//logData(data);
				//data.account = options.user_name;		
				console.log(JSON.stringify(data));
				if (data.result.state!="loginerror"){					
					//return app.createState(options.username, callback);					
					var state ={
									"account" : data.result.username,
									"token" : "",
									"nickname" : data.result.nickname,
									"id" :data.result.id,
									"telephone" :data.result.telephone
								};
			        localStorage.setItem('accountname',data.result.username);
			        mui.toast("登录成功！");
					return app.setState(state);
				    
				}
				else{
					mui.toast("用户名或密码错误！");
					return callback('用户名或密码错误');
				}
				
			},
			error:function(xhr,type,errorThrown){
				
			}
		});
	}
	
	
	//第三方用户登陆
	w.ajax_otherlogin = function(options,callback){
		var datas = JSON.stringify(options);
		console.log("第三方参数 " + JSON.stringify(datas));
		var Url = httpUrl + "usermembert/other/"
		mui.ajax(Url,{
			data:datas,
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){				
				console.log("第三方登录返回: " +JSON.stringify(data));
				//alert(JSON.stringify(data))
				if(data.reason!="OK")
				{
					mui.toast("用户名或密码错误！");
					return false;
				}					
				if (data.result.state=="otherusernamegetsuccees" || data.result.state=="otherusernamesavesuccees"){
//				    getusermemberinfo(data.result.id);//获取用户详细			    
				   
				    //alert("data.result.id--->" + data.result.id);  
					localStorage.setItem('accountid',data.result.id);//用户ID
					localStorage.setItem('accountname',data.result.nickname);//登录号或昵称					
			        localStorage.setItem("accountavatar",data.result.avatar);//头像
					mui.toast("登录成功！");
					var uinfo={
						  "username": data.result.username,//登录号
						  "rewad": data.result.rewad,    //奖励积分
						  "creadit": data.result.creadit,  //剩余积分
						  "realname": data.result.realname,//真是姓名
						  "isSource": data.result.isSource,//注册来源
						  "evaluate": data.result.evaluate, //被评价次数  
						  "evaluategrade": data.result.evaluategrade,//被评价总分
						  "cash": data.result.cash,        //兑换积分数
						  "telephone": data.result.telephone,  //手机号
						  "ret": 0,         //0正常 1异常
						  "sign": data.result.sign,        //连续签到天数   
						  "signdate": data.result.signdate,        //签到状态0未签1已签   
						  "reason": "OK",   //
						  "externalid": data.result.externalid, //第三方用户ID
						  "avatar": data.result.avatar,//用户头像
						  "regdate": data.result.regdate,//注册日期
						  "nickname": data.result.nickname,//昵称
						  "id": data.result.id,  //用户ID
						  "result": data.result.state //userdetailsuccess 成功
					     };
					
					localStorage.setItem("usermember",JSON.stringify(uinfo));//清除
//					alert(JSON.stringify(uinfo));
					 //var opener = plus.webview.currentWebview().opener();
					 var opener = plus.webview.getWebviewById("template/my.html");
                     mui.fire(opener,"intdata",{});
                     setTimeout(function() {
						var curr = plus.webview.currentWebview();
                     	// curr.close("slide-out-right",300);
                    	curr.close("pop-in",durations);  
                    	return true;	
					},300);   
				}
				else if(data.result.state=="userlock")
				{
					mui.toast("用户已锁定！");
					return false;
				}
				else{
					mui.toast("用户名或密码错误！");
					//return callback('用户名或密码错误');
					return false;
				}				
			},
			error:function(xhr,type,errorThrown){
				mui.toast("网络异常！");
				return false;
			}
		});
	}
	
	//修改密码
	w.ajax_change_pwd = function(options){
		var data = getdata(options,'com.huihoo.user.change_pwd');
		mui.ajax(httpUrl,{
			data:data,
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){
//				logData(data);
//				changePwdSuccess(data);
			},
			error:function(xhr,type,errorThrown){
				
			}
		});
	}
	
	//退出登录
	w.ajax_logout = function(options){
		var data ={};// getdata(options,'com.huihoo.user.loginout');
		//mui.ajax(httpUrl,{
		mui.ajax("../json/cart.json",{
			data:data,
			dataType:'json',//服务器返回json格式数据
			type:'get',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){
				//logData(data);
				//logoutSuccess(data);
			},
			error:function(xhr,type,errorThrown){
				
			}
		});
	}
	


})(window);




function loginSuccess(data){
			//将用户信息和account分开存放是有好处的
			if ('000000' == data.code) {
//				var user = {
//					website_name:data.website_name,
//					website_logo:data.website_logo,
//					website_grade:data.website_grade,
//					website_id:data.website_id
//				}
				//将两个数据存放起来，第一个是等出之后删除，第二个只要登录之后就会记录保存
				//localStorage.setItem('user',JSON.stringify(user));
				localStorage.setItem('account',data.account);
				mui.back();
				mui.toast('登录成功');
			}
		}


//用户登录
function ajaxlogin(options){
		var data = JSON.stringify(options);
		var Url = httpUrl + "usermemberlogin/"
		mui.ajax(Url,{
			data:data,
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){
				console.log("直接登录返回：" +JSON.stringify(data));

				if(data.reason!="OK")
				{
					mui.toast("用户名或密码错误！");
					return false;
				}
				if (data.result.state=="loginsuccess"){
					//getusermemberinfo(data.result.id);//获取用户详细
					localStorage.setItem('accountid',data.result.id);//用户ID
			        localStorage.setItem('accountname',data.result.username);//登录号或昵称
			        localStorage.setItem("accountavatar",data.result.avatar);//头像
			        mui.toast("登录成功！");
//			        var opener = plus.webview.currentWebview().opener();
//                  opener.reload(false);
//                  var view = plus.webview.currentWebview();
//                  view.hide();
                    
                    var uinfo={
						  "username": data.result.username,//登录号
						  "rewad": data.result.rewad,    //奖励积分
						  "creadit": data.result.creadit,  //剩余积分
						  "realname": data.result.realname,//真是姓名
						  "isSource": data.result.isSource,//注册来源
						  "evaluate": data.result.evaluate, //被评价次数  
						  "evaluategrade": data.result.evaluategrade,//被评价总分
						  "cash": data.result.cash,        //兑换积分数
						  "telephone": data.result.telephone,  //手机号
						  "ret": 0,         //0正常 1异常
						  "sign": data.result.sign,        //连续签到天数   
						  "signdate": data.result.signdate,        //签到状态0未签1已签   
						  "reason": "OK",   //
						  "externalid": data.result.externalid, //第三方用户ID
						  "avatar": data.result.avatar,//用户头像
						  "regdate": data.result.regdate,//注册日期
						  "nickname": data.result.nickname,//昵称
						  "id": data.result.id,  //用户ID
						  "result": data.result.state //userdetailsuccess 成功
					     };
					
					localStorage.setItem("usermember",JSON.stringify(uinfo));//清除
//					alert(JSON.stringify(uinfo));
					 //var opener = plus.webview.currentWebview().opener();
					 var opener = plus.webview.getWebviewById("template/my.html");
                     mui.fire(opener,"intdata",{});
                     setTimeout(function() {
						var curr = plus.webview.currentWebview();
                     	// curr.close("slide-out-right",300);
                    	curr.close("pop-in",durations);  
                    	return true;	
					},300);         
								    
				}
				else if(data.result.state=="userlock")
				{
					mui.toast("用户已锁定！");
					return false;
				}
				else{
					mui.toast("用户名或密码错误！");
					return false;
				}				
			},
			error:function(xhr,type,errorThrown){
				return false;
			}
		});
	}

//清除缓存
function clearCache(){
	localStorage.setItem("accountid","");//清除
	localStorage.setItem('accountname',"");//登录号或昵称
	localStorage.setItem("accountavatar","");//头像
	localStorage.setItem("usermember","{}");//清除
	localStorage.setItem("update","");//每日更新数据
	localStorage.setItem("lauchFlag", "true");//欢迎画面重置
//	
//	delFile("_doc/head.jpg");
//	mui.toast("清除成功！");
}

//登出
function Logout(){
	localStorage.setItem("accountid","");//清除
	localStorage.setItem('accountname',"");//登录号或昵称
	localStorage.setItem("accountavatar","");//头像	
	
	localStorage.setItem("update","");//每日更新数据
	
	var uinfo={
	  "username": "",//登录号
	  "rewad": 0,    //奖励积分
	  "creadit": 0,  //剩余积分
	  "realname": "",//真是姓名
	  "isSource": "",//注册来源
	  "evaluate": 0, //被评价次数  
	  "evaluategrade": 0,//被评价总分
	  "cash": 0,        //兑换积分数
	  "telephone": "",  //手机号
	  "ret": 0,         //0正常 1异常
	  "sign": 0,        //连续签到天数   
	  "signdate": 0,        //签到状态0未签1已签   
	  "reason": "OK",   //
	  "externalid": "", //第三方用户ID
	  "avatar": "../images/login/unkownuser.png",//用户头像
	  "regdate": "",//注册日期
	  "nickname": "",//昵称
	  "id": "",  //用户ID
	  "result": "" //userdetailsuccess 成功
     };
	localStorage.setItem("usermember",uinfo);//清除
}


//登录验证
function isLogin(){	
	var userid = localStorage.getItem("accountid");//用户ID
//	alert("userid--->" + userid);
	if (userid!=""&&userid!=null)
	{
		_currentuser = JSON.parse(localStorage.getItem("usermember"));
		
		str = _currentuser.nickname || _currentuser.username;
		console.log("登录用户：" +str);
		console.log("app.js --> isLogin " + "_currentuser.id--->" + _currentuser.id)
		if (_currentuser!=null && _currentuser!="" && _currentuser.id != null &&  _currentuser.id!=""){
			return true;
		}
		localStorage.setItem("accountid","");//清除
		localStorage.setItem('accountname',"");//登录号或昵称
		localStorage.setItem("accountavatar","");//头像
	}
//	plus.nativeUI.alert("请登录！", function () {
//	    //plus.webview.currentWebview().close();	
//	    var openw = plus.webview.create("../template/login.html", "login.html", { scrollIndicator: 'none', scalable: false });
//	    openw.show('slide-in-bottom');
//	    
//  });                     	  
//	mui.toast("请登录");      
	return false;	
}

function trueLogin(){
	var userid = localStorage.getItem("accountid");//用户ID
	if (userid!=""&&userid!=null)
	{
		return true;
	}
	
	//mui.toast("请登录");                   	  
	return false;	
}



//短信
function sendSms(sharecontent) {
    var msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);
    msg.to = [''];
    msg.body = sharecontent;
    plus.messaging.sendMessage(msg, function () {console.log("短信发送成功！") }, function (error) {console.log("短信发送失败！")  });
}

//每日签到
function membersign(userid){	
	var options ={
		"type":"app",
		"userid":userid
	};
	var data = JSON.stringify(options);
		var Url = httpUrl + "usermember/signcreate/"
		mui.ajax(Url,{
			data:data,
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){
				//logData(data);
				//data.account = options.user_name;		
				console.log("app.js  membersign " + JSON.stringify(data));
				if (data.result=="alreadysign"){
			        mui.toast("已签到！");   
				}
				else if (data.result=="signsuccess"){
					mui.toast("签到成功！");   
				}
				else{
					mui.toast("签到出错！");
					return false;
				}
//				  var opener = plus.webview.currentWebview().opener();
//				  opener.reload(false);
				
			},
			error:function(xhr,type,errorThrown){
				console.log("每日签到异常："  +errorThrown);
				return false;
			}
		});
}

//获取用户详细
function getusermemberinfo(userid){
	var options ={
		"type":"app",
		"userid":userid
	};
	var data = JSON.stringify(options);
		var Url = httpUrl + "usermember/deatil/"
		mui.ajax(Url,{
			data:data,
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){
				console.log("app.js getusermemberinfo " + JSON.stringify(data));				
				
				if (data.ret=="0"){
			       localStorage.setItem("usermember",JSON.stringify(data));
			       _currentuser = JSON.stringify(data);
				}
				else{				
					
				}
			},
			error:function(xhr,type,errorThrown){
				console.log("获取用户信息异常："  +errorThrown);				
			}
		});	
}



  /*<img>设置图片
         *1.从本地获取,如果本地存在,则直接设置图片
         *2.如果本地不存在则联网下载,缓存到本地,再设置图片
         * */
        function setImg(imgId, loadUrl) {
                if (imgId == null || loadUrl == null) return;
                //图片下载成功 默认保存在本地相对路径的"_downloads"文件夹里面, 如"_downloads/logo.jpg"
                var filename = loadUrl.substring(loadUrl.lastIndexOf("/") + 1, loadUrl.length);
                var relativePath = "_doc/" + filename;
                //检查图片是否已存在
                plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
                    console.log("图片存在,直接设置=" + relativePath);
                    //如果文件存在,则直接设置本地图片
                    setImgFromLocal(imgId, relativePath);
                }, function(e) {
                    console.log("图片不存在,联网下载=" + relativePath);
                    //如果文件不存在,联网下载图片
                    setImgFromNet (imgId,loadUrl,relativePath);
                });
            }
        

        /*给图片标签<img>设置本地图片
         * imgId 图片标签<img>的id
         * relativePath 本地相对路径 例如:"_downloads/logo.jpg"
         */
        function setImgFromLocal(imgId, relativePath) {
                //本地相对路径("_downloads/logo.jpg")转成SD卡绝对路径("/storage/emulated/0/Android/data/io.dcloud.HBuilder/.HBuilder/downloads/logo.jpg");
                var sd_path = plus.io.convertLocalFileSystemURL(relativePath);
                //给<img>设置图片
                if(imgId!=""){
                	$id(imgId).setAttribute("src", sd_path);
                }
            }

        /*联网下载图片,并设置给<img>*/
        function setImgFromNet (imgId,loadUrl,relativePath) {
            //先设置下载中的默认图片
            if(imgId!=""){
               $id(imgId).setAttribute("src", "../images/login/unkownuser.png");
            }
            //创建下载任务
            var dtask = plus.downloader.createDownload(loadUrl, {}, function(d, status) {
                if (status == 200) {
                    //下载成功
                    console.log("下载成功=" + relativePath);
                    setImgFromLocal(imgId, d.filename);
                } else {
                    //下载失败,需删除本地临时文件,否则下次进来时会检查到图片已存在
                    console.log("下载失败=" + status+"=="+relativePath);
                    //dtask.abort();//文档描述:取消下载,删除临时文件;(但经测试临时文件没有删除,故使用delFile()方法删除);
                    if (relativePath!=null)
                        delFile(relativePath);
                }
            });
            //启动下载任务
            dtask.start();
        }

        /*删除指定文件*/
        function delFile(relativePath) {
            plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
                entry.remove(function(entry) {
                    console.log("文件删除成功==" + relativePath);
                }, function(e) {
                    console.log("文件删除失败=" + relativePath);
                });
            });
        }

    function logData(str)
    {    
//  	alert(str)
//  	mui.plusReady(function() {
//	    	try {
//	    		var self = plus.webview.currentWebview();    		
//	    		console.log("->" +str);
//	    	} catch (err) { console.log(err)}
//  	});
    }
    
    /*
     * 
     args = {
				id: 'login.html',
				url: 'user/login.html',
				aniShow: 'slide-in-right',
				duration: 200,
				params: {
					transation: 'home'
				}
			};
	 openWindowCust(args);
     * */
    //打开webview窗口
	function openWindowCust(e) {
		//alert(JSON.stringify(e));
		var aniShow = e.aniShow == undefined ? 'zoom-fade-out' : e.aniShow;
		var duration = e.duration == undefined ? 500 : e.duration;
		var view = plus.webview.getWebviewById(e.id);
		if (view) return null; //防止重复打开webview
		view = mui.openWindow({
			id: e.id,
			url: e.url,
			createNew: true, //避重复加载
			extras: {
				params: e.params //动态参数json对象
			},
			show: {
				aniShow: aniShow, //slide-in-right,pop-in
				duration: duration
			},
			waiting: {
				autoShow: false
			}
		});
		return view;
	}
	
	
 /*发送私信*/
function sendmessages(userid,taruserid,masterid,info){
	var dataVal = {
			"type": "app",
			"masterid": masterid, //标id					
			"userid": userid,  //发出者
			"taruserid":taruserid ,//接收着
			"desc":info //留言内容
	};
	
	/*test data begin*/
//					dataVal = {
//							"type": "app",
//							"masterid": "276", //标id					
//							"userid": "77",  //发出者
//							"taruserid":"11" ,//接收着
//							"desc":info+"测试测试我是颐风土石方公司，招聘司机，您可以来公司面试。找王经理联系。电话：13132707199"//留言内容
//					};
	/*test data end*/
//	alert(JSON.stringify(dataVal));
	var post_url = request_url + '/api/mail/create/';
	mui.ajax(post_url, {
		data: JSON.stringify(dataVal),
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		success: function(data) {
//					alert(JSON.stringify(data))
			//result": "mailinfoCreatesuccess
//							console.log(JSON.stringify(data));
			if(data.result=="mailinfoCreatesuccess")
			{
				mui.toast("发送成功！");
			}
			else{
				mui.toast("发送失败，请重新留言！");
			}
		},
		error: function(xhr, type, errorThrown) {
			mui.toast("网络无法连接！");
		}
	});
}	
